<template>
	<div style="overflow-x: hidden; min-height: 120vh; position: relative">
		<topNavigation :linkMsg="linkMsg"></topNavigation>
		<div style="display: flex; justify-content: center; width: 100vw">
			<div style="width: 90vw">
				<el-card shadow="hover" style="margin-bottom: 3vh">
					<el-row>
						<el-col :span="24">
							<el-input
								v-model="newSearchVal"
								placeholder="搜索文章"
								maxlength="20"
								clearable
								size="large"
							>
								<template #append>
									<el-button
										@click="search"
										style="width: 8vw"
										class="hvr-shrink"
									>
										搜索
									</el-button>
								</template>
							</el-input>
						</el-col>
					</el-row>
				</el-card>

				<div
					style="width: 85vw; margin-left: 2.5vw; margin-right: 2.5vw"
					v-loading="pageShow"
				>
					<el-row v-if="searchState === 'ok' && data.length !== 0">
						<el-col
							:span="24"
							v-for="(item, index) in data"
							:key="index"
						>
							<el-card
								shadow="hover"
								@click="pushBlog(item.id, item.uploader)"
							>
								<div>
									<div v-html="keyword(item.title)"></div>
								</div>
								<div
									style="margin-top: 2vh; margin-bottom: 3vh"
								>
									<el-text :truncated="true" type="success">{{
										blogStore.stripHtmlTags(item.content)
									}}</el-text>
								</div>
								<div style="display: flex; align-items: center">
									<div style="display: flex">
										<div>
											<el-text type="primary"
												>作者：</el-text
											>
										</div>
										<div
											v-html="keyword(item.uploader)"
										></div>
									</div>
									<div style="margin-left: 60vw">
										<el-text
											type="info"
											style="text-wrap: nowrap"
										>
											上传日期：{{
												dateStore.getNowDate(
													JSON.parse(item.uploaddate)
												)
											}}
										</el-text>
									</div>
								</div>
							</el-card>
							<el-divider
								v-if="index < data.length - 1"
								style="
									width: 80vw;
									margin-left: 2.5vw;
									margin-right: 2.5vw;
								"
								><el-icon><star-filled /></el-icon>
							</el-divider>
						</el-col>
					</el-row>

					<el-row v-else>
						<el-col :span="24">
							<el-alert
								title="Warning"
								center
								:closable="false"
								type="warning"
								show-icon
								style="position: relative; height: 10vh"
							>
								<template #default>
									<div>
										<div>
											<el-text type="warning"
												>没有查询到相关博客记录</el-text
											>
										</div>
										<div
											style="
												position: absolute;
												top: 1vh;
												right: 1vw;
											"
										>
											<el-link
												type="warning"
												@click="pushIndex"
												>回到主页</el-link
											>
										</div>
									</div>
								</template>
							</el-alert>
						</el-col>
					</el-row>
					<el-row>
						<el-col
							:span="24"
							style="
								display: flex;
								justify-content: center;
								margin: 3vh 0;
							"
						>
							<el-pagination
								v-model:current-page="currentPage"
								background
								@update:current-page="updatePage"
								:page-size="3"
								layout="prev, pager, next"
								:total="total"
							/>
						</el-col>
					</el-row>
				</div>
			</div>
		</div>
		<div style="margin-bottom: 30vh"></div>
		<pageFooter style="position: absolute; bottom: 0"></pageFooter>
	</div>
</template>

<script setup>
import { date } from '../store/date.js';
import axios from 'axios';
import { onBeforeMount, reactive } from 'vue';
import { StarFilled } from '@element-plus/icons-vue';
import topNavigation from '../components/topNavigation.vue';
import { blog } from '../store/blog.js';
import { storeToRefs } from 'pinia';
import { useRouter } from 'vue-router';
import pageFooter from '../components/pageFooter.vue';
const blogStore = blog();
const dateStore = date();
const router = useRouter();
const newSearchVal = ref('');
const currentPage = ref(1);
const pageShow = ref(false);

let { searchState, searchVal, data, total } = storeToRefs(blogStore);
newSearchVal.value = searchVal.value;
const pushBlog = (blogId, uploader) => {
	router.push({ path: '/blogPage', query: { blogId, uploader } });
};
const updatePage = async (pageNum) => {
	pageShow.value = true;
	try {
		const res = await axios({
			baseURL: 'http://localhost:5000',
			url: '/searchBlog',
			method: 'post',
			data: {
				limit: 6,
				offset: (pageNum - 1) * 6,
				searchVal: searchVal.value,
			},
		});
		if (res.data.state === 'error') {
			return ElMessage({
				message: '服务器错误',
				type: 'error',
			});
		} else if (res.data.state === 'none') {
			blogStore.$patch((state) => {
				state.searchState = 'none';
				state.searchVal = searchVal.value;
			});
		} else {
			blogStore.$patch((state) => {
				state.searchState = 'ok';
				state.searchVal = searchVal.value;
				state.data = res.data.data;
			});
			data.value = res.data.data;
		}
		setTimeout(() => {
			pageShow.value = false;
		}, 1000);
	} catch (error) {
		console.log(error);
		return ElMessage({
			message: '请检查本地网络',
			type: 'error',
		});
	}
};

// 关键字高亮
const keyword = (text) => {
	const reg = new RegExp(blogStore.$state.searchVal, 'ig');
	return text.replace(
		reg,
		`<span class='keywords'>${blogStore.$state.searchVal}</span>`
	);
};
const search = async () => {
	if (!searchVal.value) {
		return ElMessage({
			message: '您还未输入搜索内容',
			type: 'error',
		});
	} else {
		currentPage.value = 1;
		try {
			const res = await axios({
				baseURL: 'http://localhost:5000',
				url: '/getPageTotal',
				method: 'post',
				data: {
					searchVal: newSearchVal.value,
				},
			});
			if (res.data.state === 'error') {
				return ElMessage({
					title: 'Error',
					message: '服务器错误',
					type: 'error',
				});
			} else if (res.data.state === 'none') {
				return ElMessage({
					title: 'Warning',
					message: '没有查询到相关博客记录',
					type: 'warning',
				});
			} else {
				blogStore.$patch((state) => {
					state.total = res.data.pageLength;
				});
			}
		} catch (error) {
			console.log(error);
			return ElMessage({
				message: '请检查本地网络',
				type: 'error',
			});
		}
		console.log(blogStore.$state.total);
		try {
			const res = await axios({
				baseURL: 'http://localhost:5000',
				url: '/searchBlog',
				method: 'post',
				data: {
					searchVal: newSearchVal.value,
					limit: 6,
					offset: 0,
				},
			});
			if (res.data.state === 'error') {
				return ElMessage({
					message: '服务器错误',
					type: 'error',
				});
			} else if (res.data.state === 'none') {
				blogStore.$patch((state) => {
					state.searchState = 'none';
					state.searchVal = newSearchVal.value;
				});
				return router.push('/blogSearchDetail');
			} else {
				blogStore.$patch((state) => {
					state.searchState = 'ok';
					state.searchVal = newSearchVal.value;
					state.data = res.data.data;
				});

				return router.push('/blogSearchDetail');
			}
		} catch (error) {
			console.log(error);
			return ElMessage({
				message: '请检查本地网络',
				type: 'error',
			});
		}
	}
};

const linkMsg = reactive([
	{
		linkName: '文章',
		linkMethod: () => {
			router.push('/article');
		},
	},
	{
		linkName: '发现',
		linkMethod: () => {
			router.push('/discover');
		},
	},
	{
		linkName: '留言板',
		linkMethod: () => {
			router.push('/board');
		},
	},
]);
const pushIndex = () => {
	router.push('/');
};
</script>

<style scoped>
.keywords {
	font-weight: bold;
	font-size: 20px;
	color: tomato;
}
</style>
<style>
.keywords {
	font-weight: bold;
	font-size: 20px;
	color: tomato;
}
</style>
